package com.softwaredesign.springboot.controller;

import com.softwaredesign.springboot.common.Constants;
import com.softwaredesign.springboot.common.Result;
import com.softwaredesign.springboot.controller.dto.UserDTO;
import com.softwaredesign.springboot.controller.dto.UserRDTO;
import com.softwaredesign.springboot.entity.User;
import com.softwaredesign.springboot.entity.UserRole;
import com.softwaredesign.springboot.mapper.UserMapper;
import com.softwaredesign.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if ((username != null)&&(!username.isEmpty())) {
            int length = username.length();
            for(int i = 0; i < length; i++) {
                if((username.charAt(i) == ' ') || (username.charAt(i) == '\t') || (username.charAt(i) == '\n')) {
                    return Result.error(Constants.CODE_400, "参数错误");
                }
            }
        } else {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        if ((password != null)&&(!password.isEmpty())) {
            int length = password.length();
            for(int i = 0; i < length; i++) {
                if((password.charAt(i) == ' ') || (password.charAt(i) == '\t') || (password.charAt(i) == '\n')) {
                    return Result.error(Constants.CODE_400, "参数错误");
                }
            }
        } else {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO userDTO1 = userService.login(userDTO);
        if(userDTO1 == null) {
            return Result.error();
        }
        List<Integer> roleIDs = userMapper.findUserRolesByID(userDTO1.getId());
        Integer userRoleCode = 0;
        Integer userAuthorityCode = 0;
        for (int i = 0; i < roleIDs.size(); i++) {
            Integer newRoleCode = userMapper.findRoleCodeByID(roleIDs.get(i));
            userRoleCode |= newRoleCode;
            List<Integer> authorities = userMapper.findRoleAuthoritiesByID(roleIDs.get(i));
            for (int j = 0; j < authorities.size(); j++) {
                Integer newAuthorityCode = userMapper.findAuthorityCodeByID(authorities.get(j));
                userAuthorityCode |= newAuthorityCode;
            }
        }
        userDTO1.setRoleCode(userRoleCode);
        userDTO1.setAuthorityCode(userAuthorityCode);
        return Result.success(userDTO1);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRDTO userRDTO) {
        String username = userRDTO.getUsername();
        String password = userRDTO.getPassword();
        if ((username != null)&&(!username.isEmpty())) {
            int length = username.length();
            for(int i = 0; i < length; i++) {
                if((username.charAt(i) == ' ') || (username.charAt(i) == '\t') || (username.charAt(i) == '\n')) {
                    return Result.error(Constants.CODE_400, "参数错误");
                }
            }
        } else {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        if ((password != null)&&(!password.isEmpty())) {
            int length = password.length();
            for(int i = 0; i < length; i++) {
                if((password.charAt(i) == ' ') || (password.charAt(i) == '\t') || (password.charAt(i) == '\n')) {
                    return Result.error(Constants.CODE_400, "参数错误");
                }
            }
        } else {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        if(!userService.register(userRDTO)) {
            return Result.error();
        }
        return Result.success(userRDTO);
    }

    @PostMapping("/save")
    public int save(@RequestBody User user) {
        return userService.save(user);
    }

    @PostMapping("/updateAll")
    public boolean updateAll(@RequestBody UserDTO userDTO) {
        return userService.updateAll(userDTO);
    }

    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id) {
        return userMapper.deleteById(id);
    }

    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam String username,
                                        @RequestParam String nickname,
                                        @RequestParam String email,
                                        @RequestParam String phone,
                                        @RequestParam String address) {
        pageNum = (pageNum -1) * pageSize;
        username = "%" + username + "%";
        nickname = "%" + nickname + "%";
        email = "%" + email + "%";
        phone  = "%" + phone + "%";
        address = "%" +address + "%";
        List<User> data = userMapper.selectPage(pageNum, pageSize, username, nickname, email, phone, address);
        Integer total = userMapper.selectTotal(username, nickname, email, phone, address);
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);
        res.put("total", total);
        return res;
    }

    @GetMapping("/all")
    public Map<String, Object> findAll(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize) {
        pageNum = (pageNum -1) * pageSize;
        List<User> data = userMapper.findAll(pageNum, pageSize);
        Integer total = userMapper.findAllTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);
        res.put("total", total);
        return res;
    }

    @GetMapping("/userID/{id}")
    public Result findPersonalInfo(@PathVariable Integer id) {
        UserDTO userInfo = userService.findPersonalInfoByID(id);
        if (userInfo == null) {
            return Result.error();
        }
        return Result.success(userInfo);
    }

    @GetMapping("/allRole")
    public Map<String, Object> findAllRole() {
        return userService.findAllRole();
    }

    @GetMapping("/findRole")
    public Map<String, Object> findRoleOf(@RequestParam Integer userID,
                                          @RequestParam String username,
                                          @RequestParam Integer roleID,
                                          @RequestParam Integer roleCode,
                                          @RequestParam String roleName) {
        username = "%" + username + "%";
        roleName = "%" + roleName + "%";
        return userService.findRoleOf(userID, username, roleID, roleCode, roleName);
    }

    @PostMapping("/saveUserRole")
    public boolean saveUserRole(@RequestBody UserRole userRole) {
        return userService.saveUserRole(userRole);
    }

    @DeleteMapping("/deleteUserRole")
    public Integer deleteUserRole(@RequestParam Integer userID,
                                  @RequestParam Integer roleID) {
        return userMapper.deleteUserRole(userID, roleID);
    }

    @GetMapping("/allAuthority")
    public Map<String, Object> findAllAuthority() {
        return userService.findAllAuthority();
    }

    @GetMapping("/findAuthority")
    public Map<String, Object> findAuthorityOf(@RequestParam Integer userID) {
        return userService.findAuthorityOf(userID);
    }
}
